package com.swjd.service;

import com.swjd.domain.Comment;
import com.swjd.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

/*
业务逻辑层
 */
@Service
@Transactional
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    /*
    查询：根据id查询
     */
    @Cacheable(cacheNames = "comment",unless = "#result==null")//开启缓存 存在名为comment的缓存空间中 返回值为null则不进行缓存存储
    public Comment findById(Integer id) {
        Optional<Comment> byId = commentRepository.findById(id);
        //判断如果查询到的数据不为空
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }
    /*
    更新
     */
    @CachePut(cacheNames = "comment",key = "#result.id")
    public Comment updateComment(Comment comment){
        int i = commentRepository.updateComment(comment.getAuthor(), comment.getId());
        Optional<Comment> byId2 = commentRepository.findById(comment.getId());
        if (byId2.isPresent()) {
            return byId2.get();
        }
        return null;
    }
    /*
    删除
     */
    @CacheEvict(cacheNames = "comment")
    public void deleteById(Integer id){
        commentRepository.deleteById(id);

    }

}
